﻿#pragma once
#include <list>
#include <vector>

template<class T>
class MemPool
{
public:
    MemPool();
    ~MemPool();

    T* alloc();
    void free(T* t);
    void destroy();

private:
    std::vector<T*> m_allocList;
    std::vector<T*> m_freeList;
};

template<class T>
inline MemPool<T>::MemPool()
{
}

template<class T>
inline MemPool<T>::~MemPool()
{
    destroy();
}

template<class T>
inline T * MemPool<T>::alloc()
{
    T* t = nullptr;
    if (m_freeList.empty()) {
        t = new T;
        m_allocList.push_back(t);
    }
    else {
        t = m_freeList.back();
        m_freeList.pop_back();
    }
    return t;
}

template<class T>
inline void MemPool<T>::free(T* t)
{
    m_freeList.push_back(t);
}

template<class T>
inline void MemPool<T>::destroy()
{
    for (T* t : m_allocList) {
        delete t;
    }
    m_allocList.clear();
    m_freeList.clear();
    m_allocList.shrink_to_fit();
    m_freeList.shrink_to_fit();
}
